import React, { useState, useEffect } from 'react';
import { ModelViewer } from '../components/ModelViewer';
import { RELATION_TYPES } from '../utils/constants';
import './HerbDetail.css';

interface HerbDetailProps {
  herbId: string;
  onBack: () => void;
}

interface Herb {
  id: string;
  name: string;
  category: string;
  properties: {
    性: string;
    味: string[];
  };
  functions: string[];
  toxicity: boolean;
  description?: string;
  commonUsage?: boolean;
  origin?: [number, number];
  historicalOrigins?: {
    [key: string]: [number, number] | null;
  };
  model?: string;
  pairs?: string[];
  versionChanges?: {
    [key: string]: string;
  };
}

interface HerbRelation {
  source: string;
  target: string;
  strength: number;
  type: string;
}

interface RelatedHerb {
  herb: Herb;
  relation: {
    type: string;
    strength: number;
  };
}

export const HerbDetail: React.FC<HerbDetailProps> = ({ herbId, onBack }) => {
  const [herb, setHerb] = useState<Herb | null>(null);
  const [relatedHerbs, setRelatedHerbs] = useState<RelatedHerb[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedTab, setSelectedTab] = useState<'info' | 'properties' | 'relations' | 'history'>('info');
  const [relations, setRelations] = useState<HerbRelation[]>([]);
  const [allHerbs, setAllHerbs] = useState<{[key: string]: Herb}>({});
  const [historicalQuotes, setHistoricalQuotes] = useState<{period: string, quote: string, source: string}[]>([]);

  useEffect(() => {
    const loadData = async () => {
      try {
        setIsLoading(true);
        
        // 加载药材数据
        const herbsResponse = await fetch('/src/data/herbs_extended.json');
        const herbsData = await herbsResponse.json();
        setAllHerbs(herbsData);
        
        if (herbId && herbsData[herbId]) {
          setHerb(herbsData[herbId]);
        }
        
        // 加载关系数据
        try {
          const relationsResponse = await fetch('/src/data/relations.csv');
          const relationsText = await relationsResponse.text();
          const relationsList = parseRelationsCSV(relationsText);
          setRelations(relationsList);
        } catch (error) {
          console.error('Failed to load relations:', error);
          setRelations([]);
        }
        
        // 加载历史评价数据 (模拟数据)
        if (herbId) {
          setHistoricalQuotes(generateHistoricalQuotes(herbId));
        }
        
      } catch (error) {
        console.error('Error loading data:', error);
      } finally {
        setIsLoading(false);
      }
    };
    
    loadData();
  }, [herbId]);
  
  // 当关系数据和药材数据都加载后，查找相关药材
  useEffect(() => {
    if (!herb || !relations.length || !Object.keys(allHerbs).length) return;
    
    const relatedItems = relations
      .filter(rel => rel.source === herb.id || rel.target === herb.id)
      .map(rel => {
        const otherId = rel.source === herb.id ? rel.target : rel.source;
        const otherHerb = allHerbs[otherId];
        
        if (!otherHerb) return null;
        
        return {
          herb: otherHerb,
          relation: {
            type: rel.type,
            strength: rel.strength
          }
        };
      })
      .filter((item): item is RelatedHerb => item !== null)
      .sort((a, b) => b.relation.strength - a.relation.strength);
    
    setRelatedHerbs(relatedItems);
  }, [herb, relations, allHerbs]);

  // CSV解析函数
  const parseRelationsCSV = (csv: string): HerbRelation[] => {
    const lines = csv.split('\n');
    const relations: HerbRelation[] = [];
    
    // 跳过标题行
    for (let i = 1; i < lines.length; i++) {
      const line = lines[i].trim();
      if (!line) continue;
      
      const [source, target, type, strength] = line.split(',');
      if (source && target && type && strength) {
        relations.push({
          source,
          target,
          type,
          strength: parseFloat(strength)
        });
      }
    }
    
    return relations;
  };

  // 生成历史评价模拟数据
  const generateHistoricalQuotes = (herbId: string): {period: string, quote: string, source: string}[] => {
    const periods = ['先秦', '汉代', '魏晋南北朝', '隋唐', '宋元', '明代', '清代', '现代'];
    const sources = [
      '《神农本草经》', '《本草纲目》', '《千金方》', 
      '《伤寒杂病论》', '《本草经疏》', '《本草蒙筌》', 
      '《本草从新》', '《本草备要》', '《现代中药学》'
    ];
    
    return periods.filter(() => Math.random() > 0.3).map(period => {
      return {
        period,
        quote: `${herbId}在${period}被广泛应用于${Math.random() > 0.5 ? '祛风湿' : '补气血'}等症状，${Math.random() > 0.5 ? '效果甚佳' : '药效稳定'}。${Math.random() > 0.7 ? '但需注意用量，过量有副作用。' : ''}`,
        source: sources[Math.floor(Math.random() * sources.length)]
      };
    });
  };

  const getRelationTypeColor = (type: string): string => {
    const relationType = RELATION_TYPES.find(r => r.name === type);
    return relationType ? relationType.color : '#888888';
  };

  const getRelationTypeDescription = (type: string): string => {
    const relationType = RELATION_TYPES.find(r => r.name === type);
    return relationType ? relationType.description : '';
  };

  if (isLoading) {
    return (
      <div className="herb-detail-page loading">
        <div className="loading-spinner"></div>
        <p>正在加载药材详情...</p>
      </div>
    );
  }

  if (!herb) {
    return (
      <div className="herb-detail-page not-found">
        <h2>未找到药材</h2>
        <p>请检查药材ID是否正确</p>
        <button className="back-button" onClick={onBack}>返回</button>
      </div>
    );
  }

  return (
    <div className="herb-detail-page">
      <div className="herb-detail-header">
        <button className="back-button" onClick={onBack}>
          <span>&#8592;</span> 返回
        </button>
        <h1>{herb.name}</h1>
        <div className="herb-tags">
          <span className="category-tag">{herb.category}</span>
          {herb.commonUsage && <span className="usage-tag">常用</span>}
          {herb.toxicity && <span className="toxicity-tag">有毒</span>}
        </div>
      </div>

      <div className="herb-content">
        <div className="herb-sidebar">
          <div className="herb-image">
            {herb.model ? (
              <ModelViewer modelName={herb.model} />
            ) : (
              <div className="placeholder-image">
                暂无3D模型
              </div>
            )}
          </div>
          
          <div className="herb-basic-info">
            <h3>基本信息</h3>
            <ul>
              <li>
                <span className="info-label">药材名称：</span>
                <span className="info-value">{herb.name}</span>
              </li>
              <li>
                <span className="info-label">药材分类：</span>
                <span className="info-value">{herb.category}</span>
              </li>
              <li>
                <span className="info-label">药性：</span>
                <span className="info-value">{herb.properties.性}</span>
              </li>
              <li>
                <span className="info-label">药味：</span>
                <span className="info-value">{herb.properties.味.join('、')}</span>
              </li>
              <li>
                <span className="info-label">毒性：</span>
                <span className="info-value">{herb.toxicity ? '有毒' : '无毒'}</span>
              </li>
              <li>
                <span className="info-label">常用度：</span>
                <span className="info-value">{herb.commonUsage ? '常用' : '不常用'}</span>
              </li>
            </ul>
          </div>
          
          <div className="tab-navigation">
            <button 
              className={selectedTab === 'info' ? 'active' : ''}
              onClick={() => setSelectedTab('info')}
            >
              综合介绍
            </button>
            <button 
              className={selectedTab === 'properties' ? 'active' : ''}
              onClick={() => setSelectedTab('properties')}
            >
              药性特点
            </button>
            <button 
              className={selectedTab === 'relations' ? 'active' : ''}
              onClick={() => setSelectedTab('relations')}
            >
              药材配伍
            </button>
            <button 
              className={selectedTab === 'history' ? 'active' : ''}
              onClick={() => setSelectedTab('history')}
            >
              历史评价
            </button>
          </div>
        </div>

        <div className="herb-main-content">
          {selectedTab === 'info' && (
            <div className="info-tab">
              <div className="tab-section">
                <h3>药材概述</h3>
                <p className="herb-description">{herb.description || '暂无描述'}</p>
              </div>
              
              <div className="tab-section">
                <h3>主要功效</h3>
                <div className="function-tags">
                  {herb.functions.map((func, index) => (
                    <span key={index} className="function-tag">{func}</span>
                  ))}
                </div>
              </div>
              
              {herb.pairs && (
                <div className="tab-section">
                  <h3>常用配伍</h3>
                  <ul className="herb-pairs">
                    {herb.pairs.map((pair, index) => (
                      <li key={index}>{pair}</li>
                    ))}
                  </ul>
                </div>
              )}
              
              <div className="tab-section">
                <h3>相关药材</h3>
                <div className="related-herbs-preview">
                  {relatedHerbs.slice(0, 5).map((related, index) => (
                    <div key={index} className="related-herb-item">
                      <span className="relation-indicator" style={{ backgroundColor: getRelationTypeColor(related.relation.type) }}></span>
                      <span className="related-herb-name">{related.herb.name}</span>
                      <span className="relation-type">{related.relation.type}</span>
                    </div>
                  ))}
                  {relatedHerbs.length > 5 && (
                    <button 
                      className="view-more-btn"
                      onClick={() => setSelectedTab('relations')}
                    >
                      查看更多相关药材
                    </button>
                  )}
                </div>
              </div>
            </div>
          )}

          {selectedTab === 'properties' && (
            <div className="properties-tab">
              <div className="tab-section">
                <h3>药性特点</h3>
                <div className="properties-grid">
                  <div className="property-card">
                    <h4>性</h4>
                    <div className="property-value">{herb.properties.性}</div>
                    <div className="property-scale">
                      <div className="scale-labels">
                        <span>寒</span>
                        <span>凉</span>
                        <span>平</span>
                        <span>温</span>
                        <span>热</span>
                      </div>
                      <div className="scale-bar">
                        <div 
                          className="scale-indicator" 
                          style={{ 
                            left: `${(() => {
                              switch(herb.properties.性) {
                                case '寒': return 10;
                                case '凉': return 30;
                                case '平': return 50;
                                case '温': return 70;
                                case '热': return 90;
                                default: return 50;
                              }
                            })()}%` 
                          }}
                        ></div>
                      </div>
                    </div>
                  </div>
                  
                  <div className="property-card">
                    <h4>味</h4>
                    <div className="property-value">{herb.properties.味.join('、')}</div>
                    <div className="taste-tags">
                      {['酸', '苦', '甘', '辛', '咸'].map(taste => (
                        <span 
                          key={taste} 
                          className={`taste-tag ${herb.properties.味.includes(taste) ? 'active' : ''}`}
                        >
                          {taste}
                        </span>
                      ))}
                    </div>
                  </div>
                  
                  <div className="property-card wide">
                    <h4>功效分析</h4>
                    <div className="functions-chart">
                      {herb.functions.map((func, index) => (
                        <div key={index} className="function-bar">
                          <span className="function-name">{func}</span>
                          <div className="bar-container">
                            <div 
                              className="bar" 
                              style={{ width: `${80 + Math.random() * 20}%` }}
                            ></div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                  
                  <div className="property-card wide">
                    <h4>归经</h4>
                    <div className="meridian-chart">
                      <img src="/assets/meridian_chart.png" alt="经络图" className="meridian-image" />
                      <div className="meridian-points">
                        {/* 这里可以根据药材的归经信息，在图上标注相应的经络点 */}
                        {herb.description?.includes('肝') && <div className="meridian-point" style={{ top: '40%', left: '35%' }} data-meridian="肝经"></div>}
                        {herb.description?.includes('心') && <div className="meridian-point" style={{ top: '30%', left: '50%' }} data-meridian="心经"></div>}
                        {herb.description?.includes('脾') && <div className="meridian-point" style={{ top: '45%', left: '55%' }} data-meridian="脾经"></div>}
                        {herb.description?.includes('肺') && <div className="meridian-point" style={{ top: '25%', left: '45%' }} data-meridian="肺经"></div>}
                        {herb.description?.includes('肾') && <div className="meridian-point" style={{ top: '60%', left: '45%' }} data-meridian="肾经"></div>}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <div className="tab-section">
                <h3>药材性能分析</h3>
                <div className="radar-chart-container">
                  <svg width="400" height="400" viewBox="0 0 200 200" className="radar-chart">
                    {/* 雷达图背景 */}
                    <polygon 
                      points="100,10 183,50 183,150 100,190 17,150 17,50" 
                      fill="none" 
                      stroke="#ddd" 
                      strokeWidth="1"
                    />
                    <polygon 
                      points="100,40 158,67 158,133 100,160 42,133 42,67" 
                      fill="none" 
                      stroke="#ddd" 
                      strokeWidth="1"
                    />
                    <polygon 
                      points="100,70 133,85 133,115 100,130 67,115 67,85" 
                      fill="none" 
                      stroke="#ddd" 
                      strokeWidth="1"
                    />
                    <line x1="100" y1="10" x2="100" y2="190" stroke="#ddd" strokeWidth="1" />
                    <line x1="17" y1="50" x2="183" y2="150" stroke="#ddd" strokeWidth="1" />
                    <line x1="17" y1="150" x2="183" y2="50" stroke="#ddd" strokeWidth="1" />
                    
                    {/* 雷达图数据多边形 */}
                    <polygon
                      points={`
                        ${100},${10 + 60 * Math.random()}
                        ${183 - 50 * Math.random()},${50 + 30 * Math.random()}
                        ${183 - 70 * Math.random()},${150 - 40 * Math.random()}
                        ${100},${190 - 80 * Math.random()}
                        ${17 + 60 * Math.random()},${150 - 30 * Math.random()}
                        ${17 + 40 * Math.random()},${50 + 40 * Math.random()}
                      `}
                      fill="rgba(141, 77, 59, 0.6)"
                      stroke="rgba(141, 77, 59, 0.8)"
                      strokeWidth="2"
                    />
                    
                    {/* 坐标轴标签 */}
                    <text x="100" y="5" textAnchor="middle" fontSize="10">补益</text>
                    <text x="190" y="50" textAnchor="start" fontSize="10">温热</text>
                    <text x="190" y="155" textAnchor="start" fontSize="10">清热</text>
                    <text x="100" y="198" textAnchor="middle" fontSize="10">解表</text>
                    <text x="10" y="155" textAnchor="end" fontSize="10">活血</text>
                    <text x="10" y="50" textAnchor="end" fontSize="10">利水</text>
                  </svg>
                </div>
                <div className="properties-analysis">
                  <p>
                    {herb.name}为{herb.properties.性}性{herb.properties.味.join('')}味药材，
                    其主要功效集中在{herb.functions[0]}、{herb.functions[1]}等方面。
                    作为{herb.category}类药材，具有典型的{herb.properties.性}性特点，
                    在临床应用中{herb.toxicity ? '需谨慎使用，控制剂量' : '使用安全范围较广'}。
                  </p>
                </div>
              </div>
            </div>
          )}

          {selectedTab === 'relations' && (
            <div className="relations-tab">
              <div className="tab-section">
                <h3>药材配伍关系</h3>
                <div className="relations-grid">
                  {relatedHerbs.map((related, index) => (
                    <div key={index} className="relation-card">
                      <div className="relation-header" style={{ borderColor: getRelationTypeColor(related.relation.type) }}>
                        <span className="relation-herb-name">{related.herb.name}</span>
                        <span className="relation-type-badge" style={{ backgroundColor: getRelationTypeColor(related.relation.type) }}>
                          {related.relation.type}
                        </span>
                      </div>
                      <div className="relation-content">
                        <p className="relation-description">
                          {getRelationTypeDescription(related.relation.type)}
                        </p>
                        <div className="relation-herbs-info">
                          <div className="herb-property">
                            <span className="property-label">性质：</span>
                            <span className="property-value">{related.herb.properties.性}</span>
                          </div>
                          <div className="herb-property">
                            <span className="property-label">味道：</span>
                            <span className="property-value">{related.herb.properties.味.join('、')}</span>
                          </div>
                        </div>
                        <div className="relation-strength">
                          <span className="strength-label">配伍强度：</span>
                          <div className="strength-bar-container">
                            <div 
                              className="strength-bar" 
                              style={{ 
                                width: `${related.relation.strength * 100}%`,
                                backgroundColor: getRelationTypeColor(related.relation.type)
                              }}
                            ></div>
                          </div>
                          <span className="strength-value">{Math.round(related.relation.strength * 100)}%</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              
              <div className="tab-section">
                <h3>推荐配伍方剂</h3>
                <div className="recommended-formulas">
                  {/* 这里可根据实际数据渲染推荐方剂，目前使用模拟数据 */}
                  {['四物汤', '补中益气汤', '柴胡桂枝汤'].map((formula, index) => (
                    <div key={index} className="formula-card">
                      <h4>{formula}</h4>
                      <p>主要功效：{['补血调经', '健脾益气', '和解少阳'][index]}</p>
                      <p>配伍药材：{herb.name}、{relatedHerbs[index]?.herb.name || '黄芪'}、{relatedHerbs[index+1]?.herb.name || '甘草'}</p>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {selectedTab === 'history' && (
            <div className="history-tab">
              <div className="tab-section">
                <h3>历代本草记载</h3>
                <div className="historical-timeline">
                  {historicalQuotes.map((item, index) => (
                    <div key={index} className="timeline-item">
                      <div className="timeline-period">{item.period}</div>
                      <div className="timeline-content">
                        <blockquote className="historical-quote">
                          "{item.quote}"
                        </blockquote>
                        <div className="quote-source">—— {item.source}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              
              {herb.versionChanges && (
                <div className="tab-section">
                  <h3>版本变迁</h3>
                  <div className="version-changes">
                    {Object.entries(herb.versionChanges).map(([version, description], index) => (
                      <div key={index} className="version-card">
                        <h4>{version}</h4>
                        <p>{description}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              
              <div className="tab-section">
                <h3>历史应用概述</h3>
                <div className="historical-summary">
                  <p>
                    {herb.name}自古以来就是重要的中药材，在历代医书中均有详细记载。
                    主要用于治疗{herb.functions.slice(0, 2).join('、')}等症状，历代医家对其评价颇高。
                    {herb.commonUsage 
                      ? `作为常用药材，${herb.name}在临床实践中积累了丰富的应用经验。` 
                      : `虽非常用药材，但${herb.name}在特定病症治疗中仍有独特价值。`
                    }
                    从先秦至今，对其功效认识逐渐深入，应用范围也不断扩大。
                  </p>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}; 